package com.example.discard;

import com.example.Constant;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author zhanghui
 * @date 2021/12/6 11:43
 */
public class DiscardClient {
    public static void main(String[] args) throws IOException {
        startClient();
    }

    public static void startClient() throws IOException {
        // 获取通道并配置
        InetSocketAddress serverAddress = new InetSocketAddress(Constant.SERVER_IP, Constant.SERVER_PORT);
        SocketChannel socketChannel = SocketChannel.open(serverAddress);
        socketChannel.configureBlocking(false);
        // 等待通道连接完成
        while (!socketChannel.finishConnect()) {

        }

        System.out.println("客户端连接成功");

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("请输入 (quit退出): ");
            String msg = scanner.next();
            if ("quit".equals(msg)) {
                break;
            }
            buffer.put(msg.getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }

        socketChannel.shutdownOutput();
        socketChannel.close();
    }
}
